package com.zsc.wxm.ysh.anjo.house.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zsc.wxm.ysh.anjo.house.cache.PromiseCacheService;
import com.zsc.wxm.ysh.anjo.house.cache.ResourcesCacheService;
import com.zsc.wxm.ysh.anjo.house.model.Promise;
import com.zsc.wxm.ysh.anjo.house.model.Resources;
import com.zsc.wxm.ysh.anjo.house.service.PromiseService;
import com.zsc.wxm.ysh.anjo.house.service.ResourcesService;
import com.zsc.wxm.ysh.anjo.service.base.enums.resources.HouseStatus;
import com.zsc.wxm.ysh.anjo.service.base.enums.resources.PromiseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 描述：
 *
 * @author playmaker
 * @since 2021/3/10 21:36
 */
@Slf4j(topic = "更新合约状态定时任务")
@Component
public class UpdatePromiseStatusTask {

    @Resource
    private PromiseService promiseService;

    @Resource
    private PromiseCacheService promiseCacheService;

    @Resource
    private ResourcesService resourcesService;

    @Resource
    private ResourcesCacheService resourcesCacheService;

    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateStatus() {
        long start = System.currentTimeMillis();
        LambdaQueryWrapper<Promise> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ge(Promise::getEndTime, LocalDateTime.now()).eq(Promise::getStatus, PromiseStatus.FULFILLING.getValue());
        List<Promise> list = promiseService.list(lambdaQueryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            for (Promise promise : list) {
                Resources resources = resourcesCacheService.getByIdCache(promise.getHouseId());
                //更新房源状态为空置中，因为合约已结束
                resources.setStatus(HouseStatus.AVAILABLE.getValue());
                resourcesService.updateById(resources);
                resourcesCacheService.removeByIdCache(resources.getId());
                //更新合约状态
                promise.setStatus(PromiseStatus.FINNISH.getValue());
            }
            //批量更新
            promiseService.updateBatchById(list);
            //清除缓存
            list.forEach(x -> promiseCacheService.removeListByHouseIdCache(x.getHouseId()));
        }
        log.info("UpdatePromiseStatusTask定时任务执行结束，消耗的时间: {}ms", System.currentTimeMillis() - start);

    }
}
